const { graphql, buildSchema } = require('graphql')
const express = require('express')
const { graphqlHTTP } = require('express-graphql')
const cors = require('cors')
const { v4: uuidv4 } = require('uuid')

const app = express()

app.use(cors())

const articles = [
  {id: '1', title: 'article 1', body: 'article body 1'},
  {id: '2', title: 'article 2', body: 'article body 2'},
  {id: '3', title: 'article 3', body: 'article body 3'}
]

// 1. 使用Graphql schema语法构建一个schema
const schema = buildSchema(`
  type Article {
    id: ID
    title: String
    body: String
  }

  type Query {
    articles: [Article]
    article(id: ID!): Article
  }

  type DeleteStatus {
    success: Boolean!
  }

  # 参数对象必须使用input定义
  input CreateArticleInput {
    title: String!
    body: String!
  }

  input UpdateArticleInput {
    title: String!
  }

  # 增加&修改
  type Mutation {
    createArticle(article: CreateArticleInput): Article
    updateArticle(id: ID!, article: UpdateArticleInput): Article
    deleteArticle(id: ID!): DeleteStatus
  }
`)

// 2. 定义schema的resolver
const rootValue = {
  articles() {
    return articles
  },
  article({ id }) {
    return articles.find(article => article.id === id)
  },
  createArticle({ article }) {
    article.id = uuidv4()
    articles.push(article)
    return article
  },
  updateArticle({ id, article }) {
    const art = articles.find(article => id === article.id)
    art.title = article.title
    return art
  },
  deleteArticle({ id }) {
    const index = articles.findIndex(article => article.id === id)
    console.log('--index', index)
    articles.splice(index, 1)
    return {
      success: true
    }
  }
}

// 3. 挂载Graphql中间件
app.use('/graphql', graphqlHTTP({
  schema,
  rootValue,
  graphiql: true // 开启调试IDE
}))

app.listen(4000, () => {
  console.log('Graphql Server is running')
})


// query getAllArticles {
//   articles {
//     id title
//   }
// }

// mutation deleteArticle {
//   deleteArticle(id: "1") {
//     success
//   }
// }


// mutation createArticle {
//   createArticle(article: {title: "article 4", body: "article body 4"}) {
//     id
//     title
//     body
//   }
// }




// mutation updateArticle {
//   updateArticle(id: "2", article: {title: "文章 4"}) {
//     id
//     title
//     body
//   }
// }



// mutation createArticle {
//   createArticle(article: {title: "article 4", body: "article body 4"}) {
//     id
//     title
//     body
//   }
// }